﻿using System;
using System.Collections.Generic;
using System.Text;
using FieldLib;
using FieldDevice.ModBus;


namespace FieldDevice.Emulation
{
    class REF542plusEmulator:DeviceEmulator
    {
        public REF542plusEmulator(ushort address)
            : base(address)
        { 
            
        }

        public const ushort ADDR_Ia = 0;


        byte[] ModBuffer = new byte[1 + 2 + 2 + 256 * 2 + 2 + 2 + 1];
        int DataLen;
        public override byte[] ProcessModBusPacket(ModBusPacket packet)
        {
            ModBuffer[0] = packet.SlaveAddress;
            ModBuffer[1] = packet.Function;
            ModBusPacket tmpPacket = packet;
            tmpPacket = CRCVerify(tmpPacket);
            if (packet.CRCH != tmpPacket.CRCH || packet.CRCL != tmpPacket.CRCL)
            {
                packet.DataNumberHi = 0x00;
                packet.DataNumberLow = 0x00;
            }

            switch (packet.Function)
            {
                case ModBus.ModBusFunction.READHOLDINGREGISTER:
                    ReadRegister(packet);
                    break;
                default:
                    break;
            }
            packet = CRCVerify(packet);
            ModBuffer[2 * DataLen + 3] = packet.CRCH;
            ModBuffer[2 * DataLen + 4] = packet.CRCL;
            return ModBuffer;
        }

        public void ReadRegister(ModBusPacket input)
        {
            ushort tmpAddressData;
            short tmpData;
            tmpAddressData = input.DataAddressHi;
            tmpAddressData <<= 8;
            tmpAddressData += input.DataAddressLow;
            DataLen = input.DataNumberHi;
            DataLen <<= 8;
            DataLen += input.DataNumberLow;
            ModBuffer[2] = (byte)DataLen;
            for (int i = 0; i < DataLen; i++)
            {
                tmpData = (short)RegisterValue(tmpAddressData + i);
                ModBuffer[2 * i + 3] = (byte)(tmpData >> 8);
                ModBuffer[2 * i + 4] = (byte)(tmpData & 0xff);
            }
        }


        private float RegisterValue(int addr)
         {
                float value = 0;
                switch (addr)
                {
                    default:
                        break;
                }
                return value;
          }
    
    }

}
